package com.duyus.controller;

import com.duyus.pojo.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.PublicKey;

@Slf4j
@RestController
public class SessionController {

    // 设置cookie
    @GetMapping("c1")
    public Result cookie(HttpServletResponse response){
        response.addCookie(new Cookie("login_username","duyus"));
        return Result.success();
    }

    // 获取cookir
    @GetMapping("c2")
    public Result cookiee(HttpServletRequest request){
        Cookie[] cookies  = request.getCookies(); // 获取所有的cookiee
        for (Cookie cookie : cookies){
            if (cookie.getName().equals(("login_username"))){
                System.out.println("login_username:"+cookie.getValue());
            }
        }
        return Result.success();
    }
    // 往 HttpSession里面存储值
    @GetMapping("s1")
    public Result session(HttpSession session){
        log.info("HttpSession:{}",session.hashCode());
        session.setAttribute("loginUser","tom"); // 在session中存储数据
        return Result.success();
    }

    // 从HttpSession里面取值
    @GetMapping("s2")
    public Result session2(HttpServletRequest request){
        HttpSession session = request.getSession();
        log.info("HttpSession:{}",session.hashCode());
        Object loginUser = session.getAttribute("loginUser");  // 从session中获取数据
        log.info("loginUser:{}",loginUser);
        return Result.success(loginUser);
    }

}
